package com.rightsidetech.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.PageRequest;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.system.dtos.request.store.*;
import com.rightsidetech.system.dtos.response.store.*;
import com.rightsidetech.system.entity.SysAgentInfo;
import com.rightsidetech.system.entity.store.*;
import com.rightsidetech.system.mapper.*;
import com.rightsidetech.system.service.SysStoreInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Package: com.rightsidetech.system.service.impl
 * @ClassName: SysStoreInfoServiceImpl
 * @Author: yinj
 * @CreateTime: 2021/10/20 15:17
 */
@Slf4j
@Service("sysStoreInfoServiceImpl")
public class SysStoreInfoServiceImpl implements SysStoreInfoService {

    @Resource
    private SysStoreInfoMapper sysStoreInfoMapper;

    @Resource
    private SysStoreAccountInfoMapper sysStoreAccountInfoMapper;
    @Resource
    private SysAgentInfoMapper sysAgentInfoMapper;
    @Resource
    private SysStoreLoginInfoMapper sysStoreLoginInfoMapper;
    @Resource
    private SysStoreLoginHistoryMapper sysStoreLoginHistoryMapper;
    @Resource
    private SysStoreAddressMapper sysStoreAddressMapper;
    @Resource
    private SysStoreGradeMapper sysStoreGradeMapper;


    @Override
    public ResponseData<PageInfo<SysStoreInfoResp>> page(SysStoreInfoReq request) {
        PageHelper.startPage(request.getPageNo(), request.getPageSize());
        List<SysStoreInfoResp> list = sysStoreInfoMapper.list(request);
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public ResponseData add(AddSysStoreInfoReq request,String provice, String city, String area) {

        SysAgentInfo sysAgentInfo = sysAgentInfoMapper.selectByPrimaryKey(request.getSysAgentInfoId());
        if (ObjectUtils.isEmpty(sysAgentInfo)) {
            return ResponseData.fail(CodeIdEnum.NOACCOUNT);
        }

        SysStoreInfo sysStoreInfo = sysStoreInfoMapper.selectByStoreName(request.getStoreName());
        if (!ObjectUtils.isEmpty(sysStoreInfo)) {
            return ResponseData.fail(CodeIdEnum.REPEATSTORE);
        }
        sysStoreInfo = sysStoreInfoMapper.selectByPhoneNo(request.getConnectWay());
        if (!ObjectUtils.isEmpty(sysStoreInfo)) {
            return ResponseData.fail(CodeIdEnum.REPEATPHONE);
        }

        SysStoreInfo info = new SysStoreInfo();
        info.setStoreName(request.getStoreName());
        info.setStoreImage(request.getStoreImage());
        info.setCodeImage(request.getCodeImage());
        info.setStoreNumber(request.getStoreNumber());
        info.setStoreImage(request.getStoreImage());
        info.setStoreBoss(request.getStoreBoss());
        info.setConnectWay(request.getConnectWay());
        info.setSysAgentInfoId(request.getSysAgentInfoId());
        info.setAreaId(sysAgentInfo.getAreaId());//大区id
        info.setLongitude(request.getLongitude());
        info.setLatitude(request.getLatitude());
        info.setAdress(request.getAdress());
        info.setDoorplate(request.getDoorplate());
        info.setCreatedAt(new Date());
        SysStoreGrade sysStoreGrade = sysStoreGradeMapper.findOne();
        if (!ObjectUtils.isEmpty(sysStoreGrade) && !StringUtils.isEmpty(sysStoreGrade.getLevelName())){
            info.setGradeName(sysStoreGrade.getLevelName());
        }
        else {
            info.setGradeName("普通门店");
        }

        sysStoreInfoMapper.insertSelective(info);

        SysStoreAccountInfo accountInfo = new SysStoreAccountInfo();
        accountInfo.setStoreId(info.getId());
        accountInfo.setPhoneNo(request.getConnectWay());
        accountInfo.setUpdatedAt(new Date());
        sysStoreAccountInfoMapper.insertSelective(accountInfo);

        SysStoreAddress recordAddress = new SysStoreAddress();
        recordAddress.setStoreInfoId(info.getId());
        recordAddress.setStoreName(info.getStoreBoss());
        recordAddress.setStorePhone(info.getConnectWay());
        recordAddress.setProvince(provice);
        recordAddress.setCity(city);
        recordAddress.setArea(area);
        recordAddress.setAddress(request.getAdress());
        recordAddress.setDoorplate(request.getDoorplate());
        recordAddress.setLongitude(request.getLongitude());
        recordAddress.setLatitude(request.getLatitude());
        recordAddress.setIsDefault((byte)1);
        recordAddress.setCreatedAt(new Date());
        recordAddress.setIsDeleted((byte)0);
        sysStoreAddressMapper.insertSelective(recordAddress);

        return ResponseData.success();
    }

    @Override
    public String getMaxStoreNo() {
        return sysStoreInfoMapper.getMaxStoreNo();
    }

    @Override
    public ResponseData update(UpdateSysStoreInfoReq request,SysStoreInfo sysStoreInfo) {

        if(StringUtils.isEmpty(sysStoreInfo)){
            sysStoreInfo = sysStoreInfoMapper.selectByPrimaryKey(request.getId());
            if (ObjectUtils.isEmpty(sysStoreInfo)) {
                return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
            }
        }

        sysStoreInfo = sysStoreInfoMapper.selectByAgentInfoId(request.getId(), request.getSysAgentInfoId());
        if (ObjectUtils.isEmpty(sysStoreInfo)) {
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }

        sysStoreInfo = sysStoreInfoMapper.selectByStoreName(request.getStoreName());
        if (!ObjectUtils.isEmpty(sysStoreInfo) && !sysStoreInfo.getId().equals(request.getId())) {
            return ResponseData.fail(CodeIdEnum.REPEATSTORE);
        }
        sysStoreInfo = sysStoreInfoMapper.selectByPhoneNo(request.getConnectWay());
        if (!ObjectUtils.isEmpty(sysStoreInfo) && !sysStoreInfo.getId().equals(request.getId())) {
            return ResponseData.fail(CodeIdEnum.REPEATPHONE);
        }

        SysStoreInfo info = new SysStoreInfo();
        info.setStoreName(request.getStoreName());
        info.setStoreImage(request.getStoreImage());
        info.setStoreBoss(request.getStoreBoss());
        info.setConnectWay(request.getConnectWay());
        info.setSysAgentInfoId(request.getSysAgentInfoId());
        info.setLongitude(request.getLongitude());
        info.setLatitude(request.getLatitude());
        info.setAdress(request.getAdress());
        info.setDoorplate(request.getDoorplate());
        info.setUpdatedAt(new Date());
        info.setId(request.getId());
        sysStoreInfoMapper.updateByPrimaryKeySelective(info);

        return ResponseData.success();


    }

    @Override
    public ResponseData<SysStoreInfoResp> findDetails(Long id, Long agentInfoId) {
        SysStoreInfoResp resp = sysStoreInfoMapper.findDetails(id, agentInfoId);
        if (ObjectUtils.isEmpty(resp)) {
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        return ResponseData.success(resp);
    }

    @Override
    public ResponseData open(Long id, Byte status, Long agentInfoId) {
        SysStoreInfo sysStoreInfo = sysStoreInfoMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(sysStoreInfo)) {
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        sysStoreInfo = sysStoreInfoMapper.selectByAgentInfoId(id, agentInfoId);
        if (ObjectUtils.isEmpty(sysStoreInfo)) {
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }

        if (status == 1 && sysStoreInfo.getStatus() == 1) {
            return ResponseData.fail("开启状态,无需开启");
        }
        if (status == -1 && sysStoreInfo.getStatus() == -1) {
            return ResponseData.fail("关闭状态,无需关闭");
        }
        SysStoreInfo sysStoreInfo1 = new SysStoreInfo();
        sysStoreInfo1.setId(id);
        sysStoreInfo1.setStatus(status);
        sysStoreInfo1.setUpdatedAt(new Date());
        sysStoreInfoMapper.updateByPrimaryKeySelective(sysStoreInfo1);

        //关闭 有账号 给退出登录
        if (status == -1){
            SysStoreLoginInfo loginInfo = sysStoreLoginInfoMapper.selectByStoreInfoId(id);
            if (!ObjectUtils.isEmpty(loginInfo)){
                //退出登录
                sysStoreLoginInfoMapper.delToken(loginInfo.getId());

                SysStoreLoginHistory loginHistory = sysStoreLoginHistoryMapper.selectHistory(loginInfo.getId());
                Date date = new Date();
                // 原登录记录置为过期
                if (loginHistory != null
                        && loginHistory.getLogoutTime() == null) {
                    SysStoreLoginHistory history = new SysStoreLoginHistory();
                    history.setEffectiveTime(date);
                    history.setLogoutTime(date);
                    history.setLoginInfoId(loginHistory.getLoginInfoId());
                    sysStoreLoginHistoryMapper.updateBatch(history);
                }
            }
        }


        return ResponseData.success();
    }

    @Override
    public ResponseData del(Long id, Long agentInfoId) {
        SysStoreInfo sysStoreInfo = sysStoreInfoMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(sysStoreInfo)) {
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        sysStoreInfo = sysStoreInfoMapper.selectByAgentInfoId(id, agentInfoId);
        if (ObjectUtils.isEmpty(sysStoreInfo)) {
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        //判断是否绑定账号
        SysStoreLoginInfo storeLoginInfo = sysStoreLoginInfoMapper.selectByStoreInfoId(id);
        if (!ObjectUtils.isEmpty(storeLoginInfo)){
            return ResponseData.fail("已绑定账号,请删除账号后操作");
        }
        SysStoreInfo sysStoreInfo1 = new SysStoreInfo();
        sysStoreInfo1.setId(id);
        sysStoreInfo1.setIsDeleted((byte) 1);
        sysStoreInfo1.setUpdatedAt(new Date());
        sysStoreInfoMapper.updateByPrimaryKeySelective(sysStoreInfo1);
        return ResponseData.success();
    }

    @Override
    public List<StoreResp> nearestStore(UserStoreReq req) throws Exception{
        //查询最近的一个门店
        SysStoreInfo sysStoreInfo = sysStoreInfoMapper.nearestOneStore(req);
        if (ObjectUtils.isEmpty(sysStoreInfo)) {
            return null;
        }
//        SysAgentInfo sysAgentInfo = sysAgentInfoMapper.selectByPrimaryKey(sysStoreInfo.getSysAgentInfoId());
//        if (ObjectUtils.isEmpty(sysAgentInfo)) {
//            return null;
//        }

        //查询代理商下的门店
        return sysStoreInfoMapper.findByAgentInfoId(sysStoreInfo.getSysAgentInfoId(),null,(byte)1);

    }

    @Override
    public StoreResp findOne(Long id) {
        return sysStoreInfoMapper.findOne(id);
    }

    @Override
    public SysStoreOrderDetailResp findOrderDetailByStoreId(Long id) {
        return sysStoreInfoMapper.findOrderDetailByStoreId(id);
    }

    @Override
    public SysStoreAccountInfo findStoreAccountInfoByStoreId(Long storeId) {
        SysStoreAccountInfo sysStoreAccountInfo = sysStoreAccountInfoMapper.selectByStoreId(storeId);
        return sysStoreAccountInfo;
    }

    @Override
    public ResponseData<List<StoreSearchResp>> search(String content,Long agentInfoId,Long areaId) {
        List<StoreSearchResp> list = sysStoreInfoMapper.search(content,agentInfoId,null,areaId);
        return ResponseData.success(list);
    }

    @Override
    public ResponseData<List<StoreSearchResp>> searchOpen(String content,Long agentInfoId,Long areaId) {
        List<StoreSearchResp> list = sysStoreInfoMapper.search(content,agentInfoId,"1",areaId);
        return ResponseData.success(list);
    }

    @Override
    public ResponseData updateStoreOrder(Long storeId, BigDecimal actualAmout) {
        SysStoreAccountInfo sysStoreAccountInfo = sysStoreAccountInfoMapper.selectByStoreId(storeId);
        if(StringUtils.isEmpty(sysStoreAccountInfo)){
            return ResponseData.fail(CodeIdEnum.NOSTOREMSG);
        }
        sysStoreAccountInfo.setOrderNum(sysStoreAccountInfo.getOrderNum() + 1L);
        sysStoreAccountInfo.setTotalAmount(sysStoreAccountInfo.getTotalAmount().add(actualAmout));
        sysStoreAccountInfo.setUpdatedAt(new Date());
        int count = sysStoreAccountInfoMapper.updateByPrimaryKeySelective(sysStoreAccountInfo);
        if(count > 0){
            return ResponseData.success();
        }else{
            return ResponseData.fail();
        }
    }

    @Override
    public List<SysStoreInfoResp> exportStoreList(SysStoreInfoReq req) {
        return sysStoreInfoMapper.list(req);
    }

    @Override
    public Long storeAppCheckToken(String tokenStoreApp) {
        SysStoreLoginInfo loginInfo = sysStoreLoginInfoMapper.findByToken(tokenStoreApp);
        if (StringUtils.isEmpty(loginInfo)){
            log.info("未找到该用户");
            return null;
        }
        SysStoreLoginHistory sysStoreLoginHistory = sysStoreLoginHistoryMapper.selectHistory(loginInfo.getId());
        if (StringUtils.isEmpty(sysStoreLoginHistory)){
            log.info("未找到该用户");
            return null;
        }
        if (!StringUtils.isEmpty(sysStoreLoginHistory.getLogoutTime())){
            log.info("该账户已登出");
            return null;
        }else if (new Date().after (sysStoreLoginHistory.getEffectiveTime())){
            log.info("该账户有效时间过期");
            return null;
        }
        return loginInfo.getStoreId();
    }

    @Override
    public SysStoreInfo selectByPrimaryKey(Long id) {
        return sysStoreInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public SysStoreInfo selectByPrimaryKeyByStatus(Long id) {
        return sysStoreInfoMapper.selectByPrimaryKeyByStatus(id);
    }

    @Override
    public Long storeAppCheckTokenTologinId(String tokenStoreApp) {
        SysStoreLoginInfo loginInfo = sysStoreLoginInfoMapper.findByToken(tokenStoreApp);
        if (StringUtils.isEmpty(loginInfo)){
            log.info("未找到该用户");
            return null;
        }
        SysStoreLoginHistory sysStoreLoginHistory = sysStoreLoginHistoryMapper.selectHistory(loginInfo.getId());
        if (StringUtils.isEmpty(sysStoreLoginHistory)){
            log.info("未找到该用户");
            return null;
        }
        if (!StringUtils.isEmpty(sysStoreLoginHistory.getLogoutTime())){
            log.info("该账户已登出");
            return null;
        }else if (new Date().after (sysStoreLoginHistory.getEffectiveTime())){
            log.info("该账户有效时间过期");
            return null;
        }
        return loginInfo.getId();
    }

    @Override
    public ResponseData<PageInfo<StoreResp>> storePage(StoreSearchReq req, Long agentInfoId) {
        PageHelper.startPage(req.getPageNo(),req.getPageSize());
        List<StoreResp> list = sysStoreInfoMapper.findByAgentInfoId(agentInfoId,req.getSearch(),null);
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public PageInfo<TdCommodityAgentAppStoreListResp> storeOrderStatisPage(PageRequest req,Long agentInfoId) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<TdCommodityAgentAppStoreListResp> list = sysStoreInfoMapper.storeOrderStatisListByAgentId(agentInfoId);
        return new PageInfo<>(list);
    }

    @Override
    public ResponseData<StoreResp> getStoreByCode(String storeCode) {
        StoreResp storeByCode = sysStoreInfoMapper.getStoreByCode(storeCode);
        if (ObjectUtils.isEmpty(storeByCode)){
            return ResponseData.fail(CodeIdEnum.NonStoreInfo);
        }
        if (storeByCode.getStatus() != 1){
            return ResponseData.fail("门店已停止营业");
        }
        return ResponseData.success(storeByCode);
    }

    @Override
    public SysStoreInfo selectById(Long id) {
        return sysStoreInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public List<ActStoreResp> selectStoreActResp() {
        return sysStoreInfoMapper.selectStoreActResp();
    }

    @Override
    public SysStoreLoginHistory selectLoginHistoryByStoreId(Long storeId) {
        SysStoreLoginInfo storeLoginInfo = sysStoreLoginInfoMapper.selectByStoreInfoId(storeId);
        if (!ObjectUtils.isEmpty(storeLoginInfo)){
            SysStoreLoginHistory loginHistory = sysStoreLoginHistoryMapper.selectHistory(storeLoginInfo.getId());
            if (!ObjectUtils.isEmpty(loginHistory)
                    && !StringUtils.isEmpty(loginHistory.getDeviceId())
                    && !StringUtils.isEmpty(loginHistory.getDeviceType())
                    && StringUtils.isEmpty(loginHistory.getLogoutTime())) {
                return loginHistory;
            }
        }
        return null;
    }

    @Override
    public SysStoreAccountInfo selectByStoreId(Long storeId){
        return sysStoreAccountInfoMapper.selectByStoreId(storeId);
    }

    @Override
    public int updateAccountInfo(SysStoreAccountInfo accountInfo) {
        return sysStoreAccountInfoMapper.updateByPrimaryKeySelective(accountInfo);
    }

    @Override
    public List<Long> selectIdsByAreaIds(List<Long> areaIds) {
        return sysStoreInfoMapper.selectInfoIdByAreaIds(areaIds);
    }

    @Override
    public List<Long> selectIdsByAgentIds(List<Long> agentIds) {
        return sysStoreInfoMapper.selectInfoIdByAgentIds(agentIds);
    }

    @Override
    public SysStoreInfo findNearStoreInfo(BigDecimal Longitude, BigDecimal Latitude) {
        return sysStoreInfoMapper.findLastNearByLonAndLat(Longitude, Latitude);
    }

    @Override
    public SysStoreOrderDetailResp findStoreByStoreId(Long storeId) {
        return sysStoreInfoMapper.selectByStoreId(storeId);
    }

    @Override
    public List<SysStoreInfo> selectBaseByAgentIds(List<Long> agentIds) {
        return sysStoreInfoMapper.selectByAgentIdList(agentIds);
    }

    @Override
    public Long selectCountByAgentId(List<Long> agentIds) {
        return sysStoreInfoMapper.selectCountByAgentId(agentIds);
    }

    @Override
    public Long selectAgentIdByStoreId(Long storeInfoId) {
        return sysStoreInfoMapper.selectAgentIdByStoreId(storeInfoId);
    }

    @Override
    public StoreResp selectStoreInfoById(Long id){
        return sysStoreInfoMapper.selectStoreInfoById(id);
    }
}
